<!--
 * @version: V2.1.2_点位查询方案排斥
 * @date: 2022-12-14 14:12:44
 * @description: 点位查询功能
 * @fileName: searchPoint.vue
 * @author: chenxu
!-->
<template>
    <!-- 抽屉 -->
    <el-drawer
        :model-value="modelValue"
        title="查询空位"
        :size="592"
        custom-class="search-point"
        @closed="handleClose"
        @opened="handleOpen"
    >
        <el-form ref="addFormRef" v-loading="drawerLoading" :model="pointForm" label-position="top" inline>
            <el-form-item label="投放时间" prop="city" class="item-width item-margin">
                <el-date-picker
                    v-model="pointForm.publishTime"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    clearable
                    :disabled-date="disabledDate"
                />
            </el-form-item>
            <el-form-item label="投放城市" prop="city" class="item-width">
                <el-select v-model="pointForm.city" filterable placeholder="请选择">
                    <el-option
                        v-for="item in cityList"
                        :key="item.cityCode"
                        :label="item.city"
                        :value="item.cityCode"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="投放行业" prop="trade" class="item-width item-margin">
                <el-select v-model="pointForm.trade" filterable placeholder="请选择">
                    <el-option v-for="item in secondTradeList" :key="item.code" :label="item.name" :value="item.code" />
                </el-select>
            </el-form-item>
            <el-form-item label="投放时长" prop="seconds" class="item-width">
                <el-select v-model="pointForm.seconds" filterable placeholder="请选择">
                    <el-option v-for="(item, key) in durationType" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
            <el-form-item label="投放频次" prop="numbers" class="item-width item-margin">
                <el-select v-if="mediaType === 1" v-model="pointForm.numbers" filterable placeholder="请选择">
                    <el-option v-for="(item, key) in numbersType" :key="key" :label="item" :value="key" />
                </el-select>
                <el-select v-if="mediaType === 2" v-model="pointForm.numbers" filterable placeholder="请选择">
                    <el-option v-for="(item, key) in numbersTypeOut" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
            <el-form-item label="屏幕类型" prop="type" class="item-width">
                <el-select v-model="pointForm.type" filterable placeholder="请选择">
                    <el-option
                        v-for="item in screenTypeList2"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="选点方式" prop="deliveryMode" class="item-width item-margin">
                <el-select v-model="pointForm.deliveryMode" filterable placeholder="请选择">
                    <el-option v-for="(item, key) in deliveryModeType" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
            <el-form-item v-if="mediaType === 1" label="物业类型" prop="premisesType" class="item-width">
                <el-select v-model="pointForm.premisesType" multiple collapse-tags filterable placeholder="请选择">
                    <el-option v-for="(item, key) in propertyType" :key="key" :label="item" :value="key" />
                </el-select>
            </el-form-item>
            <el-form-item v-if="mediaType === 1" label="是否联网" prop="pointStatus" class="item-width">
                <el-select v-model="pointForm.pointStatus" filterable placeholder="请选择">
                    <el-option v-for="item in isNetwork" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
        </el-form>
        <div v-loading="downloadLoading">
            <h3 class="upload-title">多坐标查询</h3>
            <el-form ref="uploadFormRef" class="upload-form" label-position="top">
                <el-form-item label="1.下载多坐标查询模板">
                    <el-button size="large" class="import-button" @click="downloadTemplateFunc">
                        <span>下载模板</span>
                    </el-button>
                </el-form-item>
                <el-form-item label="2.按照模版填写文件，然后上传坐标文件">
                    <xc-upload
                        ref="upload"
                        :http-request="httpRequest"
                        :limit="1"
                        :drag="true"
                        :history-length="uploadFileList && uploadFileList.uid ? 1 : 0"
                        tips-des="仅可上传1个文件，支持csv、xls等excel文件"
                        action=""
                        @remove="handleRemove"
                    ></xc-upload>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div>
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" :loading="drawerLoading" @click="confirmClick">导出查询结果</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, defineProps, computed, defineEmits, watch } from 'vue';
import XcUpload from '@x-tech/fe-pc-components/src/components/XcUpload/index.vue';
import {
    isNetwork,
    propertyType,
    deliveryModeType,
    screenTypeList2,
    numbersType,
    numbersTypeOut,
    durationType,
} from '@/utils/config';
import { customHttp } from '@/api/common';
import { getSecondTradeList } from '@/api/plan';
import { searchEmptyExport } from '@/api/point';
import { useStore } from 'vuex';
import { downLoadCommon } from '@/utils/common';
import { MessageBox } from '@element-plus/icons';

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false,
    },
    mediaType: {
        type: Number,
        default: 1,
    },
});

const emits = defineEmits<{(e: 'update:modelValue', visible: boolean): void; (e: 'success'): void }>();

const store = useStore();
const drawerLoading = ref(false);
const downloadLoading = ref(false);
const cityList = computed(() => store.state.userGroup.userInfo?.cityList);
const headers = computed(() => {
    let token = '';
    try {
        const { accessToken } = JSON.parse(store.state.puma.token);
        token = accessToken;
    } catch (e) {
        MessageBox.error('登录已经失效，请重新登录');
        return;
    }
    return {
        Authorization: 'Bearer ' + token,
        'Content-Type': 'multipart/form-data',
    };
});
const secondTradeList = ref([]);
console.log('window.XCConfig.VITE_URL', window.XCConfig.VITE_URL);
const importPointUrl = window.XCConfig.VITE_URL + '/saas/order/point/coordinate/upload';
let pointForm = reactive({
    beginTime: '',
    city: '',
    deliveryMode: '001',
    endTime: '',
    ignoreTaboo: 0,
    locations: null,
    numbers: '001',
    pointStatus: '0',
    premisesType: ['11', '12', '13', '14'],
    seconds: '003',
    trade: '',
    type: '003',
    publishTime: '',
});

watch(
    () => props.mediaType,
    (val) => {
        // 进来默认选中001
        pointForm.numbers = '001';
    }
);

// 获取行业数据
const getIndustryOptions = async () => {
    drawerLoading.value = true;
    try {
        secondTradeList.value = await getSecondTradeList();
        if (!secondTradeList.value) {
            secondTradeList.value = [];
        }
    } catch (e) {
        console.log('e', e);
    } finally {
        drawerLoading.value = false;
    }
};

watch(
    () => pointForm.publishTime,
    (val) => {
        console.log('publishTime', val);
        if (val && val.length) {
            pointForm.beginTime = pointForm.publishTime[0];
            pointForm.endTime = pointForm.publishTime[1];
        } else {
            pointForm.beginTime = '';
            pointForm.endTime = '';
        }
    }
);
const upload = ref(null);
let uploadFileList = reactive({ uid: '' });
const handleClose = () => {
    pointForm.locations = null;
    uploadFileList = Object.assign(uploadFileList, { uid: '' });
    upload.value.$refs.elUpload.clearFiles();
    emits('update:modelValue', false);
};

const handleOpen = async () => {
    await getIndustryOptions();
    let chooseCity = cityList.value && cityList.value.length > 0 ? cityList.value[0].cityCode : '';
    let chooseTradde = secondTradeList.value && secondTradeList.value.length > 0 ? secondTradeList.value[0].code : '';
    if (!pointForm.trade) {
        pointForm.trade = chooseTradde;
    }
    if (!pointForm.city) {
        pointForm.city = chooseCity;
    }
};

const downloadTemplateFunc = async () => {
    let res
        = 'https://setpoint.obs.cn-east-2.myhuaweicloud.com/other/2019-05-17/%E5%9D%90%E6%A0%87%E4%BF%A1%E6%81%AF%E8%A1%A8.xlsx';
    downLoadCommon(res);
};

const confirmClick = async () => {
    // console.log('confirmClick pointForm', pointForm);
    let locations = pointForm.locations || [];
    let [first] = locations;
    drawerLoading.value = true;
    try {
        let res = await searchEmptyExport({
            ...pointForm,
            locations: first && first.coordinate ? locations : null,
            mediaType: props.mediaType,
        });
        downLoadCommon(res);
    } catch (error) {
        console.log(error);
    } finally {
        drawerLoading.value = false;
    }
};
// 上传文件
const httpRequest = async (rawFile: any): Promise<void> => {
    let formData = new window.FormData();
    formData.append('file', rawFile.file);
    console.log('rawFile', rawFile);
    uploadFileList = Object.assign(uploadFileList, { name: rawFile.file.name, uid: rawFile.file.uid });
    console.log('uploadFileList', uploadFileList);
    downloadLoading.value = true;
    customHttp({
        data: formData,
        url: importPointUrl,
        headers: headers.value,
        method: 'post',
    })
        .then((res) => {
            if (res.data && res.data.data) {
                pointForm.locations = res.data.data;
            }
        })
        .catch((e) => {
            console.log('e', e);
        })
        .finally(() => {
            downloadLoading.value = false;
        });
};
const handleRemove = (file: any) => {
    pointForm.locations = null;
    uploadFileList = Object.assign(uploadFileList, { uid: '' });
    console.log('handleRemove uploadFileList', uploadFileList);
};

const disabledDate = (date: any) => {
    let now = new Date();
    let onDay = 1 * 24 * 60 * 60 * 1000; // 一天毫秒数
    return (
        // 新需求——当天23点20分前，投放开始时间支持选择当天至180天以内的时间
        +date + onDay - 40 * 60 * 1000 < +now || +date > +now + 180 * 24 * 60 * 60 * 1000
    );
};
</script>

<style lang="scss" scoped>
.search-point {
    .item-width {
        width: 260px;
        margin-right: 0;
    }

    .item-margin {
        margin-right: 16px;
    }

    .upload-title {
        font-weight: 600;
        font-size: 14px;
        color: #333333;
        letter-spacing: 0;
        margin-bottom: 20px;
    }
}
</style>
